import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:ui' as ui;


enum ImageFormat{
    jpeg,
    png
}

class ImageUtil {
    //文件路径转换成Image
    static Future<ui.Image> loadImageFromFile(String url) async {
        AssetBundle _bundle = rootBundle;
        ImageStream stream = FileImage(File.fromUri(Uri.parse(url)),).resolve(ImageConfiguration.empty);
        Completer<ui.Image> completer = Completer<ui.Image>();
        ImageStreamListener listener=ImageStreamListener((ImageInfo frame, bool synchronousCall){});
        listener =  ImageStreamListener((ImageInfo frame, bool synchronousCall) {
            final ui.Image image = frame.image;
            completer.complete(image);
            stream.removeListener(listener);
        });
        stream.addListener(listener);
        return completer.future;
    }

    //base64转图片文件
    static Future<File> createFileFromString(String base64Str,{ImageFormat format=ImageFormat.jpeg}) async {
        Uint8List bytes = base64.decode(base64Str);
        String dir = (await getApplicationDocumentsDirectory()).path;
        String ext='.jpg';
        if(format==ImageFormat.png){
            ext='.png';
        }
        File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ext);
        await file.writeAsBytes(bytes);
        return file;
    }

    //Uint8List转图片文件
    static Future<File> createFileFromUint8List(Uint8List bytes,{ImageFormat format=ImageFormat.jpeg}) async {
        String dir = (await getApplicationDocumentsDirectory()).path;
        String ext='.jpg';
        if(format==ImageFormat.png){
            ext='.png';
        }
        File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ext);
        await file.writeAsBytes(bytes);
        return file;
    }

    //网络图片转本地file
    static Future<File> getNetworkImage(String asset,{ImageFormat format=ImageFormat.jpeg}) async {
        ByteData data = await NetworkAssetBundle(Uri.parse(asset)).load(asset);
        String dir = (await getApplicationDocumentsDirectory()).path;
        String ext='.jpg';
        if(format==ImageFormat.png){
            ext='.png';
        }
        File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ext);
        await file.writeAsBytes(data.buffer.asInt8List());
        return file;
    }
}
